import axios from 'axios'
import {ElMessage} from 'element-plus'
import router from '@/router'
import store from '../store';

const request = axios.create({
    baseURL: '/api',
    timeout: 5000
})

request.interceptors.request.use(
    config => {
        const userInfo = store.state.userInfo
        if (userInfo?.token) {
            // Authorization
            config.headers['token'] = `${userInfo?.token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    async response => {
        const res = response.data
        const isFileStream = response.config.responseType === 'blob' ||
            /^(application\/octet-stream|application\/vnd.ms-excel)/.test(response.headers['content-type'])
        if (isFileStream) {
            const disposition = response.headers['content-disposition'] || ''
            const regex = disposition.match(/filename\*?=(?:utf-8'')?"?([^"]+)"?/i)
            const fileName = regex ? decodeURIComponent(regex[1]) : `file_${Date.now()}`
            const blob = new Blob([response.data], {type: response.headers['content-type']})
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link);
            return
        }

        if (res.code === 1) {
            return res.data
        }
        if (res.code === 401) {
            await router.push('/login')
        }
        ElMessage.error(res.msg || '请求失败')
        return Promise.reject(new Error(res.msg || '请求失败'))
    },
    error => {
        ElMessage.error(error.message || '请求失败')
        return Promise.reject(error)
    }
)

export default request